import React from 'react';
import { message } from 'antd';
import { useRequest } from '@/hooks';
import { queryChannelDicts } from '../../service';

const def = {};
export default function useChannelDict(channelCode, categoryCodes = []) {
    const { data, loading } = useRequest(
        () => queryChannelDicts(categoryCodes.map(item => ({ channelCode, categoryCode: item }))),
        {
            refreshDeps: [channelCode, JSON.stringify(categoryCodes)],
            formatResult: res => {
                if (res) {
                    const { code, data: resData, msg } = res;
                    if (code === 10000) {
                        if (!resData || !resData.length) {
                            return def;
                        }
                        return resData.reduce(
                            (pre, curr) => ({ ...pre, [curr.categoryCode]: curr.channelSelectList }),
                            {}
                        );
                    }
                    message.error(msg);
                }
                return def;
            }
        }
    );
    return React.useMemo(() => {
        const obj = !loading && data ? data : {};
        const next = categoryCodes.reduce((pre, curr) => ({ ...pre, [curr]: obj[curr] || [] }), {});
        return { ...next, loading };
    }, [data, loading]);
}
